package token

import (
	"github.com/golang-jwt/jwt/v5"
	"time"
)

type HS struct {
	Key string
}

// Encode 编码，将用户提供的 claims（声明）加上签名后，返回 JWT 字符串
func (hs *HS) Encode(claims jwt.Claims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(hs.Key))
}

// Decode 解码，将 JWT 字符串 sign 解码为 claims，并校验签名合法性
func (hs *HS) Decode(sign string, claims jwt.Claims) error {
	_, err := jwt.ParseWithClaims(sign, claims, func(token *jwt.Token) (interface{}, error) {
		return []byte(hs.Key), nil
	})
	return err
}

// IssueHS 用户签发Token
func IssueHS(data interface{}, expTime time.Time) (string, error) {
	claims := UserClaims{
		Data: data,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expTime),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
		},
	}

	signature, err := Hs.Encode(claims)
	return signature, err
}

// CheckHS 校验Token完整性
func CheckHS(signature string) error {
	claims := UserClaims{}
	err := Hs.Decode(signature, &claims)
	return err
}
